//
//  EHAlertPresenter.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/29.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

/// alert controller的一层包装
public class EHDialogPresenter {
    public typealias Handler = (UIAlertAction) -> ()

    /// alert action的配置信息，string对应title，any对应属性，可以设置颜色，或者图片，handler对应相应事件
    public typealias Option = (String, Any?, UIAlertAction.Style, Handler)

    /// alert controller 的title
    public var title: String?

    /// alert controller 的message
    public var message: String?

    /// alert controller 的alert action 配置
    public var options: [Option] = []

    /// alert controller 的属性title
    public var attributedTitle: NSAttributedString?

    /// alert controller 的属性message
    public var attributedMessage: NSAttributedString?

    public init() {}

    deinit {
        debugPrint("FDDialogPresenter release successfully")
    }

    /// 设置alert controller 的title
    public func setTitle(_ title: String) -> Self {
        self.title = title
        return self
    }

    /// 设置alert controller 的message
    public func setMessage(_ message: String) -> Self {
        self.message = message
        return self
    }

    /// 设置alert controller 的alert actions
    public func setOptions(_ options: [Option]) -> Self {
        self.options = options
        return self
    }

    /// 设置alert controller 的属性title
    public func setAttributedTitle(_ attrTitle: NSAttributedString) -> Self {
        self.attributedTitle = attrTitle
        return self
    }

    /// 设置alert controller 的属性message
    public func setAttributedMessage(_ attrMessage: NSAttributedString) -> Self {
        self.attributedMessage = attrMessage
        return self
    }

    /// 显示alert
    public func present(in viewController: UIViewController) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.setValue(attributedTitle, forKey: "attributedTitle")
        alertController.setValue(attributedMessage, forKey: "attributedMessage")
        addActions(to: alertController)
        viewController.present(alertController, animated: true)
    }

    /// 添加alert actions
    private func addActions(to alertController: UIAlertController) {
        options.forEach { (text, obj, style, handler) in
            let action = UIAlertAction(title: text, style: style, handler: handler)
            alertController.addAction(action)

            if let color = obj as? UIColor {
                action.setValue(color, forKey: "titleTextColor")
            }
            else if let image = obj as? UIImage {
                action.setValue(image, forKey: "image")
            }

        }
    }

}

